package org.jeecg.modules.shop.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import io.swagger.models.auth.In;
import org.apache.poi.ss.formula.functions.T;
import org.jeecg.common.util.DateUtil;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.order.entity.RsOrder;
import org.jeecg.modules.order.service.IRsOrderService;
import org.jeecg.modules.shop.entity.*;
import org.jeecg.modules.shop.service.*;
import org.jeecg.modules.shop.service.impl.RsProductServiceImpl;
import org.jeecg.modules.shop.vo.RsProductPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 商品管理
 * @Author: jeecg-boot
 * @Date: 2020-08-07
 * @Version: V1.0
 */
@Api(tags = "商品管理")
@RestController
@RequestMapping("/shop/rsProduct")
@Slf4j
public class RsProductController {
    @Autowired
    private IRsProductService rsProductService;
    @Autowired
    private IRsProductSizeService rsProductSizeService;
    @Autowired
    private IRsShopBargainService rsShopBargainService;
    @Autowired
    private IRsShopImageService rsShopImageService;
    @Autowired
    private IRsShopCommentService rsShopCommentService;
    @Resource
    private IRsOrderService rsOrderService;

    /**
     * 分页列表查询
     *
     * @param rsProduct
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "商品管理-分页列表查询")
    @ApiOperation(value = "商品管理-分页列表查询", notes = "商品管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(RsProduct rsProduct,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<RsProduct> queryWrapper = QueryGenerator.initQueryWrapper(rsProduct, req.getParameterMap());
        Page<RsProduct> page = new Page<RsProduct>(pageNo, pageSize);
        IPage<RsProduct> pageList = rsProductService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param rsProductPage
     * @return
     */
    @AutoLog(value = "商品管理-添加")
    @ApiOperation(value = "商品管理-添加", notes = "商品管理-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody RsProductPage rsProductPage) {
        RsProduct rsProduct = new RsProduct();
        BeanUtils.copyProperties(rsProductPage, rsProduct);
        rsProduct.setStatus("0");
        rsProductService.saveMain(rsProduct, rsProductPage.getRsProductSizeList(), rsProductPage.getRsShopBargainList(), rsProductPage.getRsShopImageList(), rsProductPage.getRsShopCommentList());
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param rsProductPage
     * @return
     */
    @AutoLog(value = "商品管理-编辑")
    @ApiOperation(value = "商品管理-编辑", notes = "商品管理-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody RsProductPage rsProductPage) {
        RsProduct rsProduct = new RsProduct();
        BeanUtils.copyProperties(rsProductPage, rsProduct);
        RsProduct rsProductEntity = rsProductService.getById(rsProduct.getId());
        if (rsProductEntity == null) {
            return Result.error("未找到对应数据");
        }
        rsProductService.updateMain(rsProduct, rsProductPage.getRsProductSizeList(), rsProductPage.getRsShopBargainList(), rsProductPage.getRsShopImageList(), rsProductPage.getRsShopCommentList());
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "商品管理-通过id删除")
    @ApiOperation(value = "商品管理-通过id删除", notes = "商品管理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        rsProductService.delMain(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "商品管理-批量删除")
    @ApiOperation(value = "商品管理-批量删除", notes = "商品管理-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.rsProductService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "商品管理-通过id查询")
    @ApiOperation(value = "商品管理-通过id查询", notes = "商品管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        RsProduct rsProduct = rsProductService.getById(id);
        if (rsProduct == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(rsProduct);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "产品尺码通过主表ID查询")
    @ApiOperation(value = "产品尺码主表ID查询", notes = "产品尺码-通主表ID查询")
    @GetMapping(value = "/queryRsProductSizeByMainId")
    public Result<?> queryRsProductSizeListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<RsProductSize> rsProductSizeList = rsProductSizeService.selectByMainId(id);
        return Result.ok(rsProductSizeList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "特价表通过主表ID查询")
    @ApiOperation(value = "特价表主表ID查询", notes = "特价表-通主表ID查询")
    @GetMapping(value = "/queryRsShopBargainByMainId")
    public Result<?> queryRsShopBargainListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<RsShopBargain> rsShopBargainList = rsShopBargainService.selectByMainId(id);
        return Result.ok(rsShopBargainList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "商品图片通过主表ID查询")
    @ApiOperation(value = "商品图片主表ID查询", notes = "商品图片-通主表ID查询")
    @GetMapping(value = "/queryRsShopImageByMainId")
    public Result<?> queryRsShopImageListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<RsShopImage> rsShopImageList = rsShopImageService.selectByMainId(id);
        return Result.ok(rsShopImageList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "商品评论通过主表ID查询")
    @ApiOperation(value = "商品评论主表ID查询", notes = "商品评论-通主表ID查询")
    @GetMapping(value = "/queryRsShopCommentByMainId")
    public Result<?> queryRsShopCommentListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<RsShopComment> rsShopCommentList = rsShopCommentService.selectByMainId(id);
        return Result.ok(rsShopCommentList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param rsProduct
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, RsProduct rsProduct) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<RsProduct> queryWrapper = QueryGenerator.initQueryWrapper(rsProduct, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //Step.2 获取导出数据
        List<RsProduct> queryList = rsProductService.list(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<RsProduct> rsProductList = new ArrayList<RsProduct>();
        if (oConvertUtils.isEmpty(selections)) {
            rsProductList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            rsProductList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<RsProductPage> pageList = new ArrayList<RsProductPage>();
        for (RsProduct main : rsProductList) {
            RsProductPage vo = new RsProductPage();
            BeanUtils.copyProperties(main, vo);
            List<RsProductSize> rsProductSizeList = rsProductSizeService.selectByMainId(main.getId());
            vo.setRsProductSizeList(rsProductSizeList);
            List<RsShopBargain> rsShopBargainList = rsShopBargainService.selectByMainId(main.getId());
            vo.setRsShopBargainList(rsShopBargainList);
            List<RsShopImage> rsShopImageList = rsShopImageService.selectByMainId(main.getId());
            vo.setRsShopImageList(rsShopImageList);
            List<RsShopComment> rsShopCommentList = rsShopCommentService.selectByMainId(main.getId());
            vo.setRsShopCommentList(rsShopCommentList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "商品管理列表");
        mv.addObject(NormalExcelConstants.CLASS, RsProductPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("商品管理数据", "导出人:" + sysUser.getRealname(), "商品管理"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<RsProductPage> list = ExcelImportUtil.importExcel(file.getInputStream(), RsProductPage.class, params);
                for (RsProductPage page : list) {
                    RsProduct po = new RsProduct();
                    BeanUtils.copyProperties(page, po);
                    rsProductService.saveMain(po, page.getRsProductSizeList(), page.getRsShopBargainList(), page.getRsShopImageList(), page.getRsShopCommentList());
                }
                return Result.ok("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

    /**
     * 商品上下架
     */
    @AutoLog("商品表-上架管理")
    @ApiOperation(value = "商品表-上架管理", notes = "商品表-上架管理")
    @PostMapping(value = "/putStatus")
    public Result<?> putStatus(@RequestBody Object[] ids) {
        for (int i = 0; i < ids.length; i++) {
            RsProduct product = rsProductService.getById(ids[i].toString());
            if (product == null) {
                return Result.error("未找到对应数据");
            } else {
                product.setStatus("1");
                product.setOnTime(DateUtil.getCurDate());
                rsProductService.updateById(product);
            }
        }
        return Result.ok("上架成功");
    }

    @AutoLog("商品表-下架管理")
    @ApiOperation(value = "商品表-下架管理", notes = "商品表-下架管理")
    @PostMapping(value = "/downStatus")
    public Result<?> downStatus(@RequestBody Object[] ids) {
        for (int i = 0; i < ids.length; i++) {
            RsProduct product = rsProductService.getById(ids[i].toString());
            if (product == null) {
                return Result.error("未找到对应数据");
            } else {
                product.setStatus("2");
                rsProductService.updateById(product);
            }
        }
        return Result.ok("下架成功");
    }

    /**
     * 当天商品上架列表
     */
    @AutoLog("商品表-当天商品上架列表")
    @ApiOperation(value = "商品表-当天商品上架列表", notes = "商品表-当天商品上架列表")
    @GetMapping("/getListByTime")
    public Result<?> getListByTime(HttpServletRequest request) {
        RsProduct product = new RsProduct();
        product.setOnTime(DateUtil.getCurDate());
        QueryWrapper<RsProduct> queryWrapper = QueryGenerator.initQueryWrapper(product, request.getParameterMap());
        List<RsProduct> list = rsProductService.list(queryWrapper);
        return Result.ok(list);
    }


    @AutoLog("商品表-商品信息")
    @ApiOperation(value = "商品表-商品信息", notes = "商品表-商品信息")
    @GetMapping("/getShopInfoById")
    public Result<?> getShopInfoById(@RequestParam(value = "id") String id) {
        Map<Object, Object> map = new HashMap<>();
        RsProduct rsProduct = rsProductService.getById(id);// 通过id获取商品信息
        map.put("rsProduct", rsProduct);

        List<RsShopComment> rsShopComments = rsShopCommentService.selectByMainId(rsProduct.getId()); //获取商品评论
        map.put("rsShopComments", rsShopComments);

        RsShopComment rsShopComment = new RsShopComment(); //获取评论总记录数
        rsShopComment.setProductId(rsProduct.getId());
        QueryWrapper<RsShopComment> queryWrapper = new QueryWrapper<>();
        QueryWrapper<RsShopComment> select = queryWrapper.select(rsShopComment.getProductId());
        int count = rsShopCommentService.count(select);
        map.put("count", count);

        List list1 = new ArrayList<>(); //获取产品规格
        List<RsProductSize> rsProductSizes = rsProductSizeService.selectByMainId(rsProduct.getId());
        for (RsProductSize rsProductSize : rsProductSizes) {
            list1.add(rsProductSize.getName());
        }
        map.put("list1", list1);

        List list2 = new ArrayList<>(); //获取商品图片
        List<RsShopImage> rsShopImages = rsShopImageService.selectByMainId(rsProduct.getId());
        for (RsShopImage rsShopImage : rsShopImages) {
            list2.add(rsShopImage.getUrl());
        }
        map.put("list2", list2);

        return Result.ok(map);
    }


    /**
     * 获取商品下单页信息
     */
    @AutoLog(value = "商品表-商品类型")
    @ApiOperation(value = "商品表-商品类型", notes = "商品表-商品类型")
    @GetMapping("/getShopBargain")
    public Result<?> getShopBargain(@RequestParam(value = "id") String id) {
        Map<Object, Object> map = new HashMap<>();
        RsProduct rsProduct = rsProductService.getById(id);
        List<RsShopBargain> rsShopBargains = rsShopBargainService.selectByMainId(rsProduct.getId());//商品特价信息
        map.put("rsShopBargains", rsShopBargains);

        List<RsShopImage> rsShopImages = rsShopImageService.selectByMainId(rsProduct.getId());//获取图片颜色
        map.put("rsShopImages", rsShopImages);

        List list1 = new ArrayList<>(); //产品规格
        List<RsProductSize> rsProductSizes = rsProductSizeService.selectByMainId(rsProduct.getId());
        for (RsProductSize rsProductSize : rsProductSizes) {
            list1.add(rsProductSize.getName());
        }
        map.put("list1", list1);
        return Result.ok(map);
    }

    /**
     * 判断商品活动
     */
    @AutoLog("商品表-商品活动")
    @ApiOperation(value = "商品表-商品活动", notes = "商品表-商品活动")
    @GetMapping("/getRuleId")
    public Result<?> getRuleId(@RequestParam("id") String id) {
        RsProduct rsProduct = rsProductService.getById(id);
        List<RsShopBargain> rsShopBargains=null;
        if (rsProduct.getRuleId().equals("6")){
            rsShopBargains= rsShopBargainService.selectByMainId(rsProduct.getId());
        }else {
            rsShopBargains=null;
        }
        return Result.ok(rsShopBargains);
    }


}